<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="意向城市" prop="city">-->
<!--        <el-input-->
<!--          v-model="queryParams.city"-->
<!--          placeholder="请输入意向城市"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="医院属性" prop="hospitalAttributes">-->
<!--        <el-input-->
<!--          v-model="queryParams.hospitalAttributes"-->
<!--          placeholder="请输入医院属性0-公立, 1-私立, 2-不限"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="医生性别" prop="doctorGender">-->
<!--        <el-input-->
<!--          v-model="queryParams.doctorGender"-->
<!--          placeholder="请输入医生性别"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="病种" prop="diseaseId">
        <el-input
          v-model="queryParams.diseaseId"
          placeholder="请输入病种"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="需求补充" prop="supplement">-->
<!--        <el-input-->
<!--          v-model="queryParams.supplement"-->
<!--          placeholder="请输入需求补充"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="下单时间" prop="placeOrderTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.placeOrderTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择下单时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="接单时间" prop="orderTakingTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.orderTakingTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择接单时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="完成时间" prop="completeTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.completeTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择完成时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="是否关闭会话" prop="isSession">-->
<!--        <el-input-->
<!--          v-model="queryParams.isSession"-->
<!--          placeholder="请输入是否关闭会话0-否, 1-是"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="专家ID" prop="expertId">
        <el-input
          v-model="queryParams.expertId"
          placeholder="请输入专家ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="总金额" prop="totleAmount">-->
<!--        <el-input-->
<!--          v-model="queryParams.totleAmount"-->
<!--          placeholder="请输入总金额"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="实付" prop="actualPayment">-->
<!--        <el-input-->
<!--          v-model="queryParams.actualPayment"-->
<!--          placeholder="请输入实付"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="抵扣" prop="deduction">-->
<!--        <el-input-->
<!--          v-model="queryParams.deduction"-->
<!--          placeholder="请输入抵扣"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <!-- <el-form-item label="提现状态" prop="orderStatus">
        <el-select
          v-model="queryParams.orderStatus"
          placeholder="请选择提现状态"
          clearable
        >
          <el-option label="已完成" value="0"></el-option>
          <el-option label="待接单" value="1"></el-option>
          <el-option label="进行中" value="2"></el-option>
          <el-option label="待评价" value="3"></el-option>
          <el-option label="已取消" value="5"></el-option>
        </el-select>
      </el-form-item> -->


      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

<!--    <el-row :gutter="10" class="mb8">-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['system:order:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['system:order:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['system:order:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['system:order:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="订单ID" align="center" prop="orderId" />

      <el-table-column label="用户信息" align="center" width="220">
        <template slot-scope="scope">
          <div>{{scope.row.user.nickname}}</div>
          <div>{{scope.row.user.phone}}</div>
          <div>{{scope.row.userId}}</div>
        </template>
      </el-table-column>

      <el-table-column label="专家ID" align="center" prop="expertId" />

      <el-table-column label="意向" align="center" width="140">
        <template slot-scope="scope">
          <div>{{scope.row.city}}</div>
          <div>{{formatHospitalAttributes(scope.row.hospitalAttributes)}}</div>
          <div>{{scope.row.doctorGender}}</div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="意向城市" align="center" prop="city" /> -->
      <!-- <el-table-column
          label="医院属性"
          align="center"
          prop="hospitalAttributes"
          :formatter="(row) => formatHospitalAttributes(row.hospitalAttributes)"
          width="100"
      /> -->
      <!-- <el-table-column label="医生性别" align="center" prop="doctorGender" /> -->

      <el-table-column label="病种" align="center" prop="illness">
<!--        <template slot-scope="scope">-->
<!--          {{ getDiseaseName(scope.row.diseaseId) }}-->
<!--        </template>-->
      </el-table-column>
<!--      <el-table-column label="需求补充" align="center" prop="supplement" />-->

      <el-table-column label="时间" align="center" width="240">
        <template slot-scope="scope">
          <div>{{ parseTime(scope.row.placeOrderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
          <div>{{ parseTime(scope.row.orderTakingTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
          <div>{{ parseTime(scope.row.completeTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</div>
        </template>
      </el-table-column>
<!--
      <el-table-column label="下单时间" align="center" prop="placeOrderTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.placeOrderTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="接单时间" align="center" prop="orderTakingTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.orderTakingTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="完成时间" align="center" prop="completeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.completeTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column> -->

      <el-table-column
          label="订单状态"
          align="center"
          prop="orderStatus"
          :formatter="formatOrderStatus"
      />
<!--      <el-table-column-->
<!--          label="是否关闭会话"-->
<!--          align="center"-->
<!--          prop="isSession"-->
<!--          :formatter="formatSession"-->
<!--      />-->
      <!-- <el-table-column label="用户id" align="center" prop="userId" /> -->
      <el-table-column label="总金额" align="center" prop="totleAmount" />
<!--      <el-table-column label="实付" align="center" prop="actualPayment" />-->
<!--      <el-table-column label="抵扣" align="center" prop="deduction" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >会话</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form :model="form" label-width="120px" class="detail-form">

        <!-- 左右两列展示 -->
        <el-row :gutter="20">
          <!-- 左侧：订单信息 -->
          <el-col :span="12">
            <div class="form-section-title">📦 订单信息</div>
            <el-form-item label="意向城市">
              <span>{{ form.city || '-' }}</span>
            </el-form-item>
            <el-form-item label="医院属性">
              <span>{{ formatHospitalAttributes(form.hospitalAttributes) }}</span>
            </el-form-item>
            <el-form-item label="医生性别">
              <span>{{ form.doctorGender || '-' }}</span>
            </el-form-item>
            <el-form-item label="病种">
              <span>{{ form.illness }}</span>
            </el-form-item>
            <el-form-item label="需求补充">
              <span>{{ form.supplement || '-' }}</span>
            </el-form-item>
            <el-form-item label="下单时间">
              <span>{{ formatDate(form.placeOrderTime) }}</span>
            </el-form-item>
            <el-form-item label="接单时间">
              <span>{{ formatDate(form.orderTakingTime) }}</span>
            </el-form-item>
            <el-form-item label="完成时间">
              <span>{{ formatDate(form.completeTime) }}</span>
            </el-form-item>
            <el-form-item label="是否关闭会话">
              <span>{{ formatSession(null, null, form.isSession) }}</span>
            </el-form-item>
            <el-form-item label="总金额">
              <span>{{ form.totleAmount || 0 }}</span>
            </el-form-item>
            <el-form-item label="实付">
              <span>{{ form.actualPayment || 0 }}</span>
            </el-form-item>
            <el-form-item label="抵扣">
              <span>{{ form.deduction || 0 }}</span>
            </el-form-item>
          </el-col>

          <!-- 右侧：用户信息 + 专家信息 -->
          <el-col :span="12">
            <div class="form-section-title">👤 用户信息</div>
            <el-form-item label="用户ID">
              <span>{{ form.user && form.user.userId ? form.user.userId : '-' }}</span>
            </el-form-item>
            <el-form-item label="用户姓名">
              <span>{{ form.user && form.user.name ? form.user.name : '-' }}</span>
            </el-form-item>
            <el-form-item label="用户手机号">
              <span>{{ form.user && form.user.username ? form.user.username : '-' }}</span>
            </el-form-item>

            <el-divider></el-divider>

            <div class="form-section-title">🧑‍⚕️ 专家信息</div>
            <el-form-item label="专家 ID">
              <span>{{ form.expert && form.expert.userId ? form.expert.userId : '-' }}</span>
            </el-form-item>
            <el-form-item label="专家姓名">
              <span>{{ form.expert && form.expert.name ? form.expert.name : '-' }}</span>
            </el-form-item>
            <el-form-item label="专家手机号">
              <span>{{ form.expert && form.expert.username ? form.expert.username : '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 医生库表格展示 -->
        <el-divider></el-divider>
<!--        <div class="form-section-title">📚 医生库列表</div>-->
        <el-form-item label="" style="margin-right: 150px;">
          <el-table
              :data="form.doctorLibraryList"
              border
              style="width: auto;"
          v-if="form.doctorLibraryList && form.doctorLibraryList.length"
          >
          <el-table-column prop="userId" label="ID" width="80" align="center" />
          <el-table-column prop="doctorName" label="姓名" align="center" />
          <el-table-column prop="doctorPhone" label="手机号" align="center" />
          <el-table-column prop="address" label="地址" align="center" />
          <el-table-column prop="hospital" label="医院" align="center" />
          </el-table>
          <div v-else>暂无数据</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="open1" width="900px" append-to-body>
      <el-table v-loading="loading" :data="conversationList">
        <el-table-column label="姓名" align="center" prop="fromUser" />
<!--        <el-table-column label="内容" align="center" prop="content" />-->
        <el-table-column label="内容" align="center" prop="content" width="200">
          <template slot-scope="scope">
            <div v-if="isImage(scope.row.content)">
<!--              <el-image-->
<!--                  style="width: 100px; height: 100px"-->
<!--                  :src="scope.row.content"-->
<!--                  :preview-src-list="[scope.row.content]"-->
<!--                  fit="cover"-->
<!--              />-->
              <image-preview :src="scope.row.content" :width="50" :height="50"/>
            </div>
            <span v-else>{{ scope.row.content }}</span>
          </template>
        </el-table-column>
        <el-table-column label="用户ID" align="center" prop="userId" />
        <el-table-column label="时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel1">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/order/order"
import { getListDisease } from "@/api/disease/disease"
import { listConversation } from "@/api/conversation/conversation"

export default {
  name: "Order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      hospitalAttributes1: [
        {
          value: 0,
          label: "公立"
        },
        {
          value: 1,
          label: "私立"
        },
        {
          value: 2,
          label: "不限"
        }
      ],
      orderStatus1: [
        {
          value: 0,
          label: "已完成"
        },
        {
          value: 1,
          label: "待接单"
        },
        {
          value: 2,
          label: "进行中"
        },
        {
          value: 3,
          label: "待评价"
        },
        {
          value: 4,
          label: "已评价"
        },
        {
          value: 5,
          label: "已取消"
        }
      ],
      // 是否显示弹出层
      open: false,
      open1: false,
      // 查询参数
      diseaseOptions: [],
      conversationList: [],
      // 表单参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        city: null,
        hospitalAttributes: null,
        doctorGender: null,
        diseaseId: null,
        supplement: null,
        placeOrderTime: null,
        orderTakingTime: null,
        completeTime: null,
        orderStatus: null,
        isSession: null,
        userId: null,
        expertId: null,
        totleAmount: null,
        actualPayment: null,
        deduction: null
      },
      // 表单校验
      form: {
        user: {},
        expert: {},
        doctorLibraryList: []
      },
      rules: {
      },
      conversation: {
        orderId: null
      }
    }
  },
  mounted() {
    // getListDisease().then(response => {
    //   this.diseaseOptions = response.data
    // })
  },
  created() {
    this.getList()
  },
  methods: {
    isImage(content) {
      if (!content) return false;
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.svg'];
      return imageExtensions.some(ext => content.toLowerCase().endsWith(ext));
    },
    formatDate(dateStr) {
      if (!dateStr) return '-';
      const date = new Date(dateStr);
      if (isNaN(date)) return dateStr;
      const pad = n => String(n).padStart(2, '0');
      return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
    },
    formatSession(_, __, val) {
      return val === 1 ? '是' : '否';
    },
    getDiseaseName(id) {
      const match = this.diseaseOptions.find(item => item.diseaseId === id);
      return match ? match.illnessName : '未知病种';
    },
    formatHospitalAttributes(val) {
      const map = {
        0: '公立',
        1: '私立',
        2: '不限'
      };
      return map[val] ?? '-';
    },
    formatOrderStatus(row) {
      const map = {
        '0': '已完成',
        '1': '待接单',
        '2': '进行中',
        '3': '待评价',
        '4': '已评价',
        '5': '已取消'
      };
      return map[row.orderStatus] ?? '未知';
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true
      // 先复制一份参数，避免修改 this.queryParams
      const params = {...this.queryParams};
      switch (params.hospitalAttributes) {
        case '公立':
          params.hospitalAttributes = 0;
          break;
        case '私立':
          params.hospitalAttributes = 1;
          break;
        case '不限':
          params.hospitalAttributes = 2;
          break;
          // 这里可以加default处理
      }
      switch (params.isSession) {
        case '否':
          params.isSession = 0;
          break;
        case '是':
          params.isSession = 1;
          break;
          // 这里可以加default处理
      }
      const match = this.diseaseOptions.find(item => item.illnessName === params.diseaseId);
      if (match) {
        params.diseaseId = match.diseaseId;
      }
      listOrder(params).then(response => {
        this.orderList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    cancel1() {
      this.open1 = false
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        city: null,
        hospitalAttributes: null,
        doctorGender: null,
        diseaseId: null,
        supplement: null,
        placeOrderTime: null,
        orderTakingTime: null,
        completeTime: null,
        orderStatus: null,
        isSession: null,
        userId: null,
        expertId: null,
        totleAmount: null,
        actualPayment: null,
        deduction: null,
        user: {},
        expert: {},
        doctorLibraryList: []
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加【请填写功能名称】"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const orderId = row.orderId || this.ids
      getOrder(orderId).then(response => {
        this.form = response.data
        this.open = true
        this.title = "【订单详情】"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderId = row.orderId || this.id
      this.conversation.orderId = orderId
      listConversation(this.conversation).then(response => {
        this.conversationList = response.rows
      })
      this.open1 = true
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style scoped>
.form-section-title {
  font-weight: bold;
  margin: 10px 0;
  font-size: 16px;
}
.detail-form .el-table {
  margin: 0 auto;
}
</style>

